package coco.mogodb.com.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.exceptions.PersistenceException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理: 使用 @RestControllerAdvice + @ExceptionHandler 注解方式实现全
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler({Exception.class})
    public ResponseEntity<Object> globalExceptionHandler(Exception e) {
        e.printStackTrace();
        if (e instanceof PersistenceException) {
            return new ResponseEntity<>("数据重复", HttpStatus.INTERNAL_SERVER_ERROR);
        } else {
            return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @ExceptionHandler({BizException.class})
    public ResponseEntity<Object> businessExceptionHandler(BizException e) {
        e.printStackTrace();
        return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
    }
}
